<script setup name="writeNote">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useNotePageStore, useNoteValueStore } from '@/stores'
import {
  delFatherFiled,
  setFatherFiled,
  uploadNoteText
} from '@/services/upload'
import { ElLoading } from 'element-plus' // 加载
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus' // 提示
// 混入
import { positionFn } from '@/composable'

let { noteType } = positionFn()

// 笔记状态仓库
let noteStore = useNotePageStore()
// 笔记仓库
let noteValueStore = useNoteValueStore()

let router = useRouter()

// 笔记名and笔记类型
let noteValidateForm = ref({
  noteName: '', // 笔记名
  chooseNoteType: [] // 级联类型
})
// 校验规则
let rules = ref({
  noteName: [
    { required: true, message: '必须要先填入笔记名哦！', trigger: 'blur' }
  ],
  chooseNoteType: [
    { required: true, message: '必须要先填入笔记名哦！', trigger: 'change' }
  ]
})

// 父级文件夹名，父级文件夹名刚开始是空的
let fatherFiled = ref(noteStore.fatherFiled)

// 跳转状态，是否前往了文件上传页面
let pageState = ref(noteStore.pageState)
onMounted(() => {
  // 依据跳转状态，去切换子级路由
  pageState.value
    ? router.push('/write/uploadImg')
    : router.push('/write/noteText')
})

let formRef = ref(null)
// 提交数据
async function submit() {
  // 表单校验
  formRef.value.validate().then(() => {
    // 表单校验通过
    ElMessageBox.confirm(
      `确定要把当前的<span class="el_essage_box_title">${noteValidateForm.value.noteName}</span>进行上传吗?`,
      '提示',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '我再修改一下！',
        dangerouslyUseHTMLString: true
      }
    ).then(async () => {
      // 仍然需要检测一下文档输入的合法性，比如，笔记是空的
      if (!noteValueStore.note)
        return ElMessage({
          message: '笔记不能为空啦!',
          type: 'warning'
        })
      // 字符串分解
      let arr = []
      let hs = 0
      try {
        for (let i = 0; i < noteValueStore.note.length; i++) {
          if (i >= hs + 20000) {
            // 截取一次
            arr.push(noteValueStore.note.substring(hs, i + 1))
            hs = i + 1
            // 查看剩余还有没有这么多字符
            // 游标已经到达
          } else {
            if (i + 1 === noteValueStore.note.length) {
              // 游标到头
              arr.push(noteValueStore.note.substring(hs, i + 1))
            }
          }
        }
      } catch (error) {
        console.log(error)
      }
      // 发送上传请求
      let res = await uploadNoteText({
        noteName: noteValidateForm.value.noteName, // 笔记名
        chooseNoteType:
          noteValidateForm.value.chooseNoteType[
            noteValidateForm.value.chooseNoteType.length - 1
          ], // 笔记类型（前端只能传最终值上来）
        noteList: arr,
        father: noteStore.fatherFiled // 父级文件夹名
      })
      clearAll()
      // 跳转主页
      router.push('/home')
      ElMessage({
        type: res.data.code === 10000 ? 'success' : 'error',
        message: res.data.msg
      })
    })
  })
}

function clearAll() {
  // 清空当前的所有数据
  // 清空表单
  noteValidateForm.value.noteName = ''
  noteValidateForm.value.chooseNoteType = []
  // 清空pinia
  noteValueStore.setNote('')
  noteStore.setPageState(false)
  noteStore.setFatherFiled('')
  // 清空表单
  fatherFiled.value = ''
  // 清空表单
  noteStore.setUpIsOk()
}

// 数据拆除，按照两万字为一段进行拆析
let tooltip = ref(null)
// 父级绑定
const bindingParent = async () => {
  // 上传父级绑定名
  if (!fatherFiled.value)
    return ElNotification({
      title: '猪头嘛！',
      message: '空的怎么绑定呢？',
      type: 'error',
      duration: 1200
    })
  let res = await setFatherFiled(fatherFiled.value)
  // 开启图片上传空间,写入本地存储
  noteStore.setFatherFiled(res.data)
}

// 放弃本次父级绑定
const giveUpflodName = async () => {
  // 上传父级绑定名，通知后端把文件夹整个删除
  const loadingInstance = ElLoading.service({ fullscreen: true })
  await delFatherFiled(noteStore.fatherFiled)
  loadingInstance.close()
  // 通知子组件清空数组，给子组件传参，子组件监听传参的变化
  noteStore.setEmpty()
  // 关闭上传空间
  noteStore.setFatherFiled('')
  // 清空表单
  fatherFiled.value = ''
}

// 去往home页面会清除本次书写的笔记
function goHome() {
  // 提示
  // 清空表单输入的note数据
  noteStore.setUpIsOk()
  clearAll()
}
</script>
<template>
  <div class="write-note-box">
    <!-- 顶部通栏 -->
    <!-- 图片文件上传的话，要求上传文件夹的名字 -->
    <div class="top-nav">
      <MyTransition>
        <div class="switch" v-if="!noteStore.pageState">
          <!-- 表单校验 -->
          <el-form
            ref="formRef"
            :rules="rules"
            :model="noteValidateForm"
            label-position="right"
            class="note-ruleForm"
            :inline="true"
          >
            <el-form-item label="笔记名：" prop="noteName">
              <el-input
                placeholder="例如：vue.js"
                v-model="noteValidateForm.noteName"
                class="note-name"
                :show-word-limit="true"
              />
            </el-form-item>
            <el-form-item
              label="类型："
              prop="chooseNoteType"
              class="note-type"
            >
              <el-cascader
                placeholder="搜索：前端"
                :options="noteType"
                filterable
                clearable
                :collapse-tags="true"
                collapse-tags-tooltip
                v-model="noteValidateForm.chooseNoteType"
              >
                <template v-slot:empty>没有匹配项</template>
              </el-cascader>
            </el-form-item>
          </el-form>

          <!-- 其他部分 -->
          <div>
            <button class="publishBtn home" @click="goHome">
              <router-link to="/home">home</router-link>
            </button>
          </div>
          <div>
            <Btn flag path="/write/uploadImg">图片文件上传</Btn>
          </div>
          <div>
            <button class="publishBtn" @click="submit">发布上传</button>
          </div>
        </div>
        <div class="switch" v-else>
          <div>
            父级文件夹：
            <el-input
              class="note-name"
              v-model="fatherFiled"
              :disabled="noteStore.fatherFiled ? true : false"
              placeholder="绑定之后不可再度更改！"
            />

            <!-- 绑定 -->
            <el-tooltip
              content="必须绑定后才能上传图片哦！"
              placement="bottom"
              effect="light"
              ref="tooltip"
            >
              <button
                class="publishBtn"
                :class="{ disabledBtn: noteStore.fatherFiled }"
                :disabled="noteStore.fatherFiled ? true : false"
                @click="bindingParent"
              >
                绑定
              </button>
            </el-tooltip>
            <el-popover
              placement="top-start"
              title="警告"
              :width="200"
              trigger="hover"
              content="放弃绑定后，需要重新上传全部资源！"
            >
              <template #reference>
                <button
                  class="publishBtn give-up"
                  :class="{ disabledBtn: !noteStore.fatherFiled }"
                  :disabled="!noteStore.fatherFiled ? true : false"
                  @click="giveUpflodName"
                >
                  放弃
                </button>
              </template>
            </el-popover>
          </div>
          <div>
            <Btn flag path="/write/noteText">返回笔记区</Btn>
          </div>
        </div>
      </MyTransition>
    </div>

    <!-- 子级路由 -->
    <router-view v-slot="{ Component }">
      <keep-alive>
        <component :is="Component" />
      </keep-alive>
    </router-view>
  </div>
</template>

<style lang="scss" scoped>
@use '@/styles/vueCode.css';
.write-note-box {
  // 页面最小宽
  min-width: 1110px;
  .top-nav {
    height: 13.7vh;
    border-bottom: 1px solid #dedbdb;
    background-color: #f7f7f7;
    .switch {
      height: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      background-color: #f7f7f7;
      .note-ruleForm {
        display: flex;
        align-items: center;
        .el-form-item {
          display: flex;
          align-items: center;
          margin: 0;
        }
      }
      .note-name {
        border-radius: 5px;
        border: 1px solid #f7f7f7;
        display: inline-block;
        height: 32px;
        width: 200px;
        margin-right: 40px;
      }
      .note-type {
        margin-right: 40px;
      }

      .disabledBtn {
        color: #a8abb2;
        border: 1px solid #e4e7ed;
        background-color: #f5f7fa;
      }
      .home {
        margin-left: 40px;
      }
      .disabledBtn:hover {
        cursor: not-allowed;
      }
    }
  }
}

.give-up {
  color: #f56c6c;
}
</style>
